package org.example.likou150.tree;

import java.util.HashMap;
import java.util.Map;

//  https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/?envType=study-plan-v2&envId=top-interview-150
public class BuildTree2 {
    public static void main(String[] args) {
        BuildTree2 buildTree2 = new BuildTree2();
        int[] inOrder = new int[]{9,3,15,20,7};
        int[] postOrder = new int[]{9,15,7,20,3};
        buildTree2.buildTree(inOrder, postOrder);
    }

    Map<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return build(postorder, postorder.length-1, postorder.length-1, 0);
    }

//    int[] inOrder = new int[]{9,3,15,20,7};
//    int[] postOrder = new int[]{9,15,7,20,3};
    private TreeNode build(int[] postOrder, int endIndex, int inBegin, int inEnd){
        if(inBegin < inEnd){
            return null;
        }
        int val = postOrder[endIndex];
        TreeNode treeNode = new TreeNode(val);
        Integer inIndex = map.get(val);

        treeNode.right = build(postOrder, endIndex-1, inBegin, inIndex+1);
        treeNode.left = build(postOrder, endIndex-(inBegin-inIndex)-1, inIndex-1,inEnd);

        return treeNode;
    }



    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}


